package com.example.day_day_up.utils;

import com.alibaba.fastjson.JSONObject;
import com.example.day_day_up.entity.constants.Constants;
import com.example.day_day_up.enums.ResponseCodeEnum;
import com.example.day_day_up.exception.BusinessException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class JsonUtils {
    private static final String CONTENT_TYPE_JSON = "application/json";

    public static void writeResponse(HttpServletResponse response, int code, String msg, Object data) {
        JSONObject res = new JSONObject();
        res.put(Constants.RES_CODE, code);
        res.put(Constants.RES_MSG, msg);
        if (data != null) {
            res.put(Constants.RES_DATA, data);
        }
        writeJsonResponse(response, res);
    }

    public static void writeSuccessResponse(HttpServletResponse response, String msg, Object data) {
        writeResponse(response, ResponseCodeEnum.CODE_200.getCode(), msg, data);
    }

    public static void writeSuccessResponse(HttpServletResponse response, Object data) {
        writeSuccessResponse(response, ResponseCodeEnum.CODE_200.getMsg(), data);
    }

    public static void writeSuccessResponse(HttpServletResponse response, String msg) {
        writeSuccessResponse(response, msg, null);
    }

    public static void writeSuccessResponse(HttpServletResponse response) {
        writeSuccessResponse(response, null);
    }

    public static void writeErrorResponse(HttpServletResponse response, int code, String msg) {
        writeResponse(response, code, msg, null);
    }

    public static void writeErrorResponse(HttpServletResponse response, String msg) {
        writeErrorResponse(response, ResponseCodeEnum.CODE_404.getCode(), msg);
    }

    public static void writeParameterErrorResponse(HttpServletResponse response, String msg) {
        writeErrorResponse(response, ResponseCodeEnum.CODE_600.getCode(), msg);
    }

    private static void writeJsonResponse(HttpServletResponse response, JSONObject res) {
        response.setContentType(CONTENT_TYPE_JSON);
        try (PrintWriter writer = response.getWriter()) {
            writer.write(res.toString());
        } catch (IOException e) {
            throw new BusinessException("JSON化错误");
        }
    }
}
